'use client'

import { useState, useEffect, useCallback } from 'react'
import { motion } from 'framer-motion'
import { MasonryGrid } from '@/components/MasonryGrid'
import { Header } from '@/components/Header'
import { PostCard } from '@/components/PostCard'
import { useVirtualScroll } from '@/lib/useVirtualScroll'
import { generateMockData } from '@/lib/mockData'

interface Post {
  id: string
  title: string
  content: string
  images: string[]
  author: {
    name: string
    avatar: string
  }
  likes: number
  comments: number
  tags: string[]
  createdAt: string
}

export default function HomePage() {
  const [posts, setPosts] = useState<Post[]>([])
  const [loading, setLoading] = useState(false)
  const [hasMore, setHasMore] = useState(true)

  // 生成初始数据
  useEffect(() => {
    const initialPosts = generateMockData(20)
    setPosts(initialPosts)
  }, [])

  // 加载更多数据
  const loadMore = useCallback(async () => {
    if (loading || !hasMore) return
    
    setLoading(true)
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const newPosts = generateMockData(10)
    
    if (newPosts.length === 0) {
      setHasMore(false)
    } else {
      setPosts(prev => [...prev, ...newPosts])
    }
    
    setLoading(false)
  }, [loading, hasMore])

  // 使用虚拟滚动优化
  const { containerRef } = useVirtualScroll({
    onLoadMore: loadMore,
    threshold: 100,
  })

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />
      
      <main className="container mx-auto px-4 py-6">
        <motion.div 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
        >
          <MasonryGrid 
            posts={posts}
            loading={loading}
            hasMore={hasMore}
            containerRef={containerRef}
          />
        </motion.div>
      </main>
    </div>
  )
}
